import grp
import pwd

from WebBackend.store.ConfigurationStore import ConfigurationStore


class UserStore:
    def __init__(self, config_store: ConfigurationStore):
        self.configStore = config_store
        self.local_users = []
        self.virtual_users = []
        self.reload_store()

    def reload_store(self):
        self.local_users = []
        self.virtual_users = []
        ############################################
        invalid_shells = {'/sbin/nologin', '/bin/false', '/usr/sbin/nologin', '/bin/sync', '/bin/true'}
        for user in pwd.getpwall():
            # 检查 shell 是否有效（不在无效列表里）
            if user.pw_shell not in invalid_shells:
                # 获取用户组名（由 GID 转换）
                try:
                    group_name = grp.getgrgid(user.pw_gid).gr_name
                except KeyError:
                    group_name = str(user.pw_gid)  # 如果组名不存在，返回 GID
                self.local_users.append({
                    "username": user.pw_name,
                    'uid': user.pw_uid,
                    'home': user.pw_dir,
                    "group": group_name,
                    "shell": user.pw_shell
                })
            else:
                pass
        ##############################################
